package com.cuiweiyou.uiautomator20;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.List;

/**
 * www.gaohaiyan.com
 */
@RunWith(AndroidJUnit4.class)
public class TestSearching {
    private static final String TAG = "ard";
    private static UiDevice device;
    private static Context context;
    private static String nameSplitFlag = "<<>>";

    @BeforeClass // 此方法须静态
    public static void beforeClass() throws RemoteException {
        UtilLogs.saveLog("1.BeforeClass");

        UtilFile.initSourcePath(); // searching

        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        context = instrumentation.getTargetContext().getApplicationContext();

        device = UiDevice.getInstance(instrumentation);

        if (!device.isScreenOn()) {
            device.wakeUp();
        }

        TestUtilCtrl.requestPermission(device);
        UtilSQLite.getInstance(context);
    }

    @Before
    public void before() {
        UtilLogs.saveLog("2.Before");

        int versionCode = UtilPhone.getVersionCode(context);
        String versionName = UtilPhone.getVersionName(context);

        String deviceSN = UtilPhone.getDeviceSN().toLowerCase();
        Constant.DEVICE_SN = deviceSN;

        UtilLogs.saveLog(" ");
        UtilLogs.saveLog(" ");
        UtilLogs.saveLog(" ");
        UtilLogs.saveLog("====== 开始查找新朋友 ======");

        ManagerViewID.getInstance().initSelf(deviceSN, versionName);
    }

    @After
    public void after() {
        UtilLogs.saveLog("-2.After");
    }

    @AfterClass // 此方法须静态
    public static void afterClass() {
        UtilLogs.saveLog("-1.AfterClass");
    }

    /**
     * 查找好友添加
     */
    @Test
    public void testSearching() {
        Bundle bundle = InstrumentationRegistry.getArguments();

        String phone = bundle.getString("number");

        UtilLogs.saveLog("查找好友shell指令收到微信号：" + phone);

        if (TextUtils.isEmpty(phone)) {
            UtilLogs.saveLog("查找好友shell指令没有收到微信号");
            return;
        }

        UtilLogs.saveLog("收到微信号：" + phone);

        String hello = bundle.getString("hello");
        UtilLogs.saveLog("查找好友shell指令收到问好：" + hello);
        if (null != hello && !TextUtils.isEmpty(phone)) {
            hello = hello.trim().replace("a88a", "");
        }
        if (TextUtils.isEmpty(hello)) {
            hello = "";
        }
        UtilLogs.saveLog("收到打招呼：" + hello);

        ModelFriend friend = UtilSQLite.getInstance(context).hasFriend(phone); // 执行加好友test，初始判断
        if (null != friend) {
            boolean othersideDeleted = friend.isOthersideDeleted();
            //if (othersideDeleted) {
            UtilLogs.saveLog("对方已经删除过好友关系：" + phone);
            return;
            //}
        }

        TestUtilCtrl.launcherWechatApp(device, "查找加好友");
        TestUtilCtrl.switchTab(device, "通讯录");
        TestUtilCtrl.swipeListViewToTopItem(device); // search
        scrollGotoShowNewFriendBtn(); // 查找添加朋友

        // nextAty，进入下一个界面，"新的好友"，查找好友界面

        device.wait(Until.hasObject(By.textContains("添加朋友")), 5000);

        UtilLogs.saveLog("进入 新的朋友 页面");
        TestUtilCtrl.showCurrentActivity(device, "是否为'新的好友'");

        // 添加朋友
        UiObject2 object = device.findObject(By.textContains("添加朋友"));
        object.click();

        UtilLogs.saveLog("点击了-添加朋友");

        // nextAty，进入下一个"添加朋友"界面，有多种添加方式：雷达、面对面、扫一扫等

        String search_qq_phone_keyword = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_wechat_qq_phone_keyword);
        if (null == search_qq_phone_keyword) {
            device.wait(Until.hasObject(By.textContains("微信号/QQ号/手机号")), 5000);
            object = device.findObject(By.textContains("微信号/QQ号/手机号")); // 搜索微信号/QQ号/手机号 textview
            UtilLogs.saveLog("查找1'微信号/QQ号/手机号'");
        } else {
            device.wait(Until.hasObject(By.textContains(search_qq_phone_keyword)), 5000);
            object = device.findObject(By.textContains(search_qq_phone_keyword)); // 搜索微信号/QQ号/手机号 textview
            UtilLogs.saveLog("查找2'" + search_qq_phone_keyword + "'");
        }

        TestUtilCtrl.showCurrentActivity(device, "是否为'添加朋友'");

        //String className = object.getClassName();

        object.click();
        UtilLogs.saveLog("点击了-微信号/手机号 放大镜按钮");

        // nextAty，输入界面，这里输入目标电话号码
        UtilLogs.saveLog("进入输入界面");

        String id_search_edittext_input = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_edittext_input);
        if (null == id_search_edittext_input) {
            device.wait(Until.hasObject(By.res("com.tencent.mm", "jh")), 5000);
            UtilLogs.saveLog("等待输入框：jh");
        } else {
            String id = id_search_edittext_input.replace("com.tencent.mm:id/", "");
            device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);
            UtilLogs.saveLog("等待输入框：id：" + id);
        }

        TestUtilCtrl.showCurrentActivity(device, "是否为'输入账号'");

        // 输入号码xxx，搜索xxx页面

        String search_wechat_qq_phone_keyword = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_wechat_qq_phone_keyword);
        if (null == search_wechat_qq_phone_keyword) {
            object = device.findObject(By.textContains("微信号/QQ号/手机号")); // edittext文本框界面
            UtilLogs.saveLog("查找输入框1：'微信号/QQ号/手机号'");
        } else {
            object = device.findObject(By.textContains(search_wechat_qq_phone_keyword));
            UtilLogs.saveLog("查找输入框2：'" + search_wechat_qq_phone_keyword + "'");
        }

        //className = object.getClassName();
        object.setText("");
        object.setText(phone);
        UtilLogs.saveLog("输入了-微信号/手机号：" + phone);

        Rect inputBound = object.getVisibleBounds();

        Boolean hasSearch = device.wait(Until.hasObject(By.textContains("搜索:")), 5000);
        if (hasSearch) {
            object = device.findObject(By.textContains("搜索:"));
            UtilLogs.saveLog("查找搜索动态按钮");
        } else {
            String search_the_search_btn = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_the_search_btn);
            if (null != search_the_search_btn) {
                String id = search_the_search_btn.replace("com.tencent.mm:id/", "");
                object = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("查找搜索动态按钮，id：" + id);
            } else {
                UtilLogs.saveLog("查找搜索动态按钮 失败");
            }
        }

        if (null == object) {
            String search_the_search_btn_p = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_the_search_btn_p);
            String id = search_the_search_btn_p.replace("com.tencent.mm:id/", "");
            Boolean hasR_ = device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);
            if (hasR_) {
                object = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("重新查找搜索动态按钮 id=" + id);
            } else {
                object = device.findObject(By.text("搜索:" + phone));
                UtilLogs.saveLog("重新查找搜索动态按钮 搜索:" + phone);
            }
        }

        if (null == object) {
            int x = inputBound.centerX();
            int y = inputBound.bottom + 28;
            device.click(x, y);
            UtilLogs.saveLog("手动点击了-搜索 x=" + x + "，y=" + y);
        } else {
            object.click();
            UtilLogs.saveLog("自动点击了-搜索");
        }

        // 如果查无此人，则当前页面显示"该用户不存在"。否则进入详细资料界面。

        Boolean noWxid = device.wait(Until.hasObject(By.textContains("该用户不存在")), 5000);
        if (noWxid) {
            UtilLogs.saveLog("查无此人");

            // 查无此人
            UtilSQLite.getInstance(context).insertSearch(phone, "none", "none", "none", "none");

            for (int i = 0; i < 6; i++) {
                device.pressBack();
                UtilLogs.saveLog("返回桌面 " + i);
            }

            return;
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // nextAty，如果找到了该用户，会调转到下一个界面：详细资料

        TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");
        UtilLogs.saveLog("进入详细资料页面");

        String[] friendDetails = TestUtilCtrl.getFriendDetails(device, 2); // 查找号码，加好友

        String wxid = friendDetails[0];
        String notename = friendDetails[1];
        String nickname = friendDetails[2];
        if (null == notename || (notename.trim()).length() < 1) {
            if (null != nickname && nickname.contains("昵称:") && nickname.length() > 0) {
                notename = nickname.replace("昵称:", "").trim();
            } else if (null != wxid && wxid.contains("昵称:") && wxid.length() > 0) {
                notename = wxid.replace("昵称:", "").trim();
            }
        }

        UtilLogs.saveLog("朋友的wxid：" + wxid);
        UtilLogs.saveLog("朋友的nickname：" + nickname);
        UtilLogs.saveLog("朋友的notename：" + notename);

        Boolean hasAdd2ContactObject = device.wait(Until.hasObject(By.textContains("添加到通讯录")), 5000);
        UtilLogs.saveLog("等待 添加到通讯录");

        if (hasAdd2ContactObject) { // 还不是好友

            if (!notename.contains(nameSplitFlag)) {
                UtilLogs.saveLog("称呼中没有<<>>标记，取设置");
                gotoSetNoteName(phone, notename);
            }

            // back aty 自动返回详细信息界面

            device.wait(Until.hasObject(By.textContains("添加到通讯录")), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'详细资料'");

            UtilLogs.saveLog("等待 添加到通讯录 详细资料");

            // 好友信息界面
            object = device.findObject(By.textContains("添加到通讯录"));
            object.click();
            UtilLogs.saveLog("点击了-添加到通讯录");

            // 之前加过了，我删除了对方，但对方未删除我，会直接更新为好友关系
            Boolean hasSendMsgObject = device.wait(Until.hasObject(By.textContains("发消息")), 5000);

            if (hasSendMsgObject) { // 已经添加了好友
                UtilLogs.saveLog("之前曾经，已经是好友了");

                TestUtilCtrl.showCurrentActivity(device, "是否为'发消息按钮'页面");

                UtilLogs.saveLog("查找记录入库");
                UtilSQLite.getInstance(context).insertSearch(phone, wxid, notename, nickname, "yes");

                for (int i = 0; i < 6; i++) {
                    device.pressBack(); // 返回桌面，重置下一次测试的条件
                    UtilLogs.saveLog("返回桌面 " + i);
                }

                return;
            }

            // nextAty，进入发送界面-验证申请

            device.wait(Until.hasObject(By.textContains("发送")), 5000);

            TestUtilCtrl.showCurrentActivity(device, "是否为'发送页面'");
            UtilLogs.saveLog("进入发送页面，等待 发送");

            List<UiObject2> editTexts = device.findObjects(By.clazz(EditText.class));
            for (int i = 0; i < editTexts.size(); i++) {
                UiObject2 et = editTexts.get(i);
                et.setText("");
            }
            UtilLogs.saveLog("清空了EditText");

            String id_search_sayhello = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_sayhello);
            UiObject2 hailedObj;
            if (null == id_search_sayhello) {
                hailedObj = device.findObject(By.res("com.tencent.mm", "do1")); // 打招呼消息
                UtilLogs.saveLog("查找打招呼控件 do1");
            } else {
                String id = id_search_sayhello.replace("com.tencent.mm:id/", "");
                hailedObj = device.findObject(By.res("com.tencent.mm", id)); // 打招呼消息
                UtilLogs.saveLog("查找打招呼控件 id=" + id);
            }
            hailedObj.setText(hello);
            UtilLogs.saveLog("设置打招呼 " + hello);

            String id_search_notename = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_notename);
            UiObject2 noteNameObj;
            if (null == id_search_notename) {
                noteNameObj = device.findObject(By.res("com.tencent.mm", "do5")); // 为朋友设置备注
                UtilLogs.saveLog("查找备注控件 do5 ");
            } else {
                String id = id_search_notename.replace("com.tencent.mm:id/", "");
                noteNameObj = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("查找备注控件 id= " + id);
            }

            if (!notename.contains(nameSplitFlag)) {
                notename = phone + nameSplitFlag + notename;
            }
            noteNameObj.setText(notename);
            UtilLogs.saveLog("向朋友打招呼，设置备注：" + notename);

            // 发送界面
            object = device.findObject(By.textContains("发送"));
            object.click();
            UtilLogs.saveLog("点击了-发送");

            // back aty，此时返回到“添加到通讯录”界面。
            // 一种是等待通过，仍然显示"添加到通讯录"
            // 一种是直接通过，更新显示"发消息"

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            TestUtilCtrl.showCurrentActivity(device, "是否为'添加到通讯录'");

            UtilLogs.saveLog("查找记录入库sql");
            UtilSQLite.getInstance(context).insertSearch(phone, wxid, notename, nickname, "yes");

            // 这里暂不处理，统一到聊天流程

            for (int i = 0; i < 6; i++) {
                device.pressBack(); // 返回桌面，重置下一次测试的条件
                UtilLogs.saveLog("返回桌面 " + i);
            }

            return;
        }

        // 之前加过了，已经是好友了
        Boolean hasSendMsgObject = device.wait(Until.hasObject(By.textContains("发消息")), 5000);

        if (hasSendMsgObject) { // 已经添加了好友
            UtilLogs.saveLog("已经是好友了");

            TestUtilCtrl.showCurrentActivity(device, "是否为'发消息'");

            // 这里暂不处理，统一到聊天流程

            for (int i = 0; i < 6; i++) {
                device.pressBack();  // 一次返回，即回到首页
                UtilLogs.saveLog("返回桌面 " + i);
            }

            return;
        }
    }

    /**
     * 设置备注名
     *
     * @param phone       原电话号码
     * @param oldNoteName 原备注名
     */
    private void gotoSetNoteName(String phone, String oldNoteName) {

        // 此时在"备注名"界面

        device.wait(Until.hasObject(By.textContains("设置备注")), 5000);

        UiObject2 object = device.findObject(By.textContains("设置备注"));
        object.click();
        UtilLogs.saveLog("点击了设置备注按钮");

        // nextAty 进入设置备注界面
        UtilLogs.saveLog("进入设置备注和标签页面");

        TestUtilCtrl.showCurrentActivity(device, "是否为'设置备注'");

        device.wait(Until.hasObject(By.textContains("备注名")), 5000);

        List<UiObject2> editTextList = device.findObjects(By.clazz(EditText.class));
        for (int i = 0; i < editTextList.size(); i++) {
            UiObject2 edit = editTextList.get(i);
            String editClassName = edit.getClassName(); // android.widget.EditText
            edit.setText(""); // 清空默认填入的称呼，使关键字词hint显示
        }
        UtilLogs.saveLog("清空了页面的EditTExt");

        Boolean hasObject = device.wait(Until.hasObject(By.textContains("新的备注名称")), 2000);
        if (hasObject) {
            object = device.findObject(By.textContains("新的备注名称")); // edittext文本框界面
            UtilLogs.saveLog("查找控件 新的备注名称");
        } else {
            String note_and_label_set_notename = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_note_and_label_set_notename);
            if (null != note_and_label_set_notename) {
                String id = note_and_label_set_notename.replace("com.tencent.mm:id/", "");
                object = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("查找控件 id=" + id);
            } else {
                object = device.findObject(By.res("com.tencent.mm", "b8b")); // 微信7.0.5上的id
                UtilLogs.saveLog("查找控件 使用默认id b8b");
            }
        }

        String nn = phone + nameSplitFlag + oldNoteName;
        object.setText(nn); // phone作为备注名
        UtilLogs.saveLog("设置了新的备注名称：" + nn);

        Boolean hasSave = device.wait(Until.hasObject(By.textContains("保存")), 5000);
        if (hasSave) {
            object = device.findObject(By.textContains("保存"));
            UtilLogs.saveLog("查找控件 保存");
        } else {
            hasSave = device.wait(Until.hasObject(By.textContains("完成")), 2000); // 微信7.0.5
            if (hasSave) {
                object = device.findObject(By.textContains("完成"));
                UtilLogs.saveLog("查找控件 完成");
            } else {
                UtilLogs.saveLog("查找控件 完成，失败");
            }
        }
        if (null != object) {
            object.click();
            UtilLogs.saveLog("点击了-保存新的备注名称");
        } else {
            UtilLogs.saveLog("没有找到保存或完成按钮");
        }

        // 此时自动退出"备注名"界面
    }

    /**
     * 点击"通讯录"顶部的"新的朋友"选项，进入查找好友或者查看陌生人的好友请求
     */
    private void scrollGotoShowNewFriendBtn() {
        UiObject2 lm;
        String id_cll = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_contacts_letter_list);
        if (null == id_cll) {
            device.wait(Until.hasObject(By.res("com.tencent.mm", "lm")), 5000);
            lm = device.findObject(By.res("com.tencent.mm", "lm"));// 右边的字母快捷操作条
            UtilLogs.saveLog("点击字母竖条使列表回到顶部：id：lm");
        } else {
            String id = id_cll.replace("com.tencent.mm:id/", "");
            device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);
            lm = device.findObject(By.res("com.tencent.mm", id));
            UtilLogs.saveLog("点击字母竖条使列表回到顶部：id：" + id);
        }

        if (null != lm) {
            Rect rect = lm.getVisibleBounds();
            int clickX = rect.centerX();
            int clickY = rect.top + 10;   // 向上箭头的位置
            device.click(clickX, clickY); // 点击回到ListView的顶端
            UtilLogs.saveLog("点击了字母竖条使列表：x：" + clickX + "，y：" + clickY);
        }

        Boolean hasNewFriendObject = device.wait(Until.hasObject(By.textContains("新的朋友")), 5000);
        if (hasNewFriendObject) {
            UiObject2 object = device.findObject(By.textContains("新的朋友"));
            object.click();
            UtilLogs.saveLog("点击了 新的朋友");
        } else { ////////////////////////////////////// 如有有主动的好友请求，这里关键字会被遮挡
            // com.tencent.mm:id/bm6
            Boolean hasBm6Object;

            String id_mask = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_search_contacts_friend_new_mask);
            if (null == id_mask) {
                hasBm6Object = device.wait(Until.hasObject(By.res("com.tencent.mm", "bm6")), 5000);

                UtilLogs.saveLog("有无 新的朋友 1 " + hasBm6Object);

                clickFindNewFriend(hasBm6Object, null);
            } else {
                String id = id_mask.replace("com.tencent.mm:id/", "");
                hasBm6Object = device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);

                UtilLogs.saveLog("有无 新的朋友 2 " + hasBm6Object);

                clickFindNewFriend(hasBm6Object, id);
            }
        }
    }

    private void clickFindNewFriend(boolean hasBm6Object, String id) {
        if (hasBm6Object) {
            UiObject2 object;
            if (null == id) {
                object = device.findObject(By.res("com.tencent.mm", "bm6"));
                UtilLogs.saveLog("查找 新的朋友 控件：bm6");
            } else {
                object = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("查找 新的朋友 控件：id=" + id);
            }
            object.click();
            UtilLogs.saveLog("点击了 新的朋友 控件");
        } else {
            //[28,144][672,248]
            int x = (672 - 28) / 2;
            int y = (248 - 144) / 2;
            device.click(x, y);
            UtilLogs.saveLog("点击了 新的朋友 位置 x=" + x + "，y=" + y);
        }
    }
}
